package com.eningqu.aipen.logic.network;

import android.util.Log;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Package:com.eningqu.aipen.logic.network
 * Author:starr
 * Time:11/25/2023 7:42 PM
 * Description: 管理RxJava内存泄漏的类
 */
public class RxLifecycle<T> implements LifecycleObserver, ObservableTransformer<T,T> {

    final CompositeDisposable compositeDisposable=new CompositeDisposable();
    /**
     * Android系统提供的注解，
     * 监听destroy这种生命周期
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private void onDestroy(){
        Log.i("RxLifecycle", "onDestroy: ");
        if(!compositeDisposable.isDisposed()){
            compositeDisposable.dispose();
        }
    }

    @Override
    public ObservableSource<T> apply(Observable<T> observable) {
        return observable.doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                compositeDisposable.add(disposable);
            }
        });
    }

    public static <T> RxLifecycle<T> bindExLifecycle(LifecycleOwner owner){
        RxLifecycle<T> lifecycle=new RxLifecycle<>();
        owner.getLifecycle().addObserver(lifecycle);
        return lifecycle;
    }
}
